//
//  QueryCarResult.m
//  AutoHome
//
//  Created by wqh on 15-5-13.
//  Copyright (c) 2015年 Wqh. All rights reserved.
//

#import "QueryCarResult.h"

#import "CarSystemModel.h"
#import "CarSystemCell.h"
#import "BaseGrayView.h"
#import "QFRefreshView.h"
#import "SelectCarTypeView.h"

#define kCarSystemCellId @"CarSystemCellId"


@interface QueryCarResult ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,assign) NSInteger currentPage;
@property (nonatomic,assign) BOOL isRefreshing;
@property (nonatomic) BaseGrayView *grayView;
@property (nonatomic) SelectCarTypeView *selectCarTypeView;
@end

@implementation QueryCarResult

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.title = @"筛选结果";
    self.currentPage = 1;
    
    self.dataArr = [NSMutableArray array];
    
    [self setResultButtonTitle:self.resultInfo];
    [self createTableView];
    [self downloadData];
    [self createRefreshView];
    [self createGrayView];
    [self createSelectCarTypeView];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - 创建右侧索引视图
//创建弹出透明半黑色视图
- (void)createGrayView {
    self.grayView = [[BaseGrayView alloc] initWithFrame:CGRectMake(0, 20, kScreenWidth, kScreenHeight-20)];
    [[[UIApplication sharedApplication].delegate window] addSubview:self.grayView];
    //通过block回调 让点击灰色视图后，右侧视图也能移出屏幕
    __weak typeof(self)mySelf = self;
    self.grayView.myBlock = ^ {
        mySelf.selectCarTypeView.frame = CGRectMake(kScreenWidth, 20, kScreenWidth-50, kScreenHeight-20);
    };
}

//创建右边滑动视图
- (void)createSelectCarTypeView {
    self.selectCarTypeView = [[[NSBundle mainBundle] loadNibNamed:@"SelectCarTypeView" owner:self options:nil] lastObject];
    self.selectCarTypeView.frame= CGRectMake(kScreenWidth, 20, kScreenWidth-50, kScreenHeight-20);
    [[[UIApplication sharedApplication].delegate window] addSubview:self.selectCarTypeView];
    //通过回调 让右侧视图消失
    __weak typeof(self) mySelf = self;
    self.selectCarTypeView.myCloseViewBlock = ^ {
        mySelf.grayView.alpha = 0;
    };
    
    //跳转block
    self.selectCarTypeView.myJumpPageBlock = ^(UIViewController *vc) {
        
        mySelf.grayView.alpha = 0 ;
        mySelf.selectCarTypeView.frame = CGRectMake(kScreenWidth, 20, kScreenWidth-50, kScreenHeight-20);
        [mySelf.navigationController pushViewController:vc animated:YES];
    };
}

#pragma mark - 创建底部显示查询结果的按钮
- (void)setResultButtonTitle:(NSArray *)array {
    NSString *system = [array[0] stringValue];
    NSString *total = [array[1] stringValue];
    [self.resultButton setTitle:[NSString stringWithFormat:@"共%@个车系%@个车型",system,total] forState:UIControlStateNormal];
}

#pragma mark - 刷新
- (void)createRefreshView {
    
    //下拉刷新
    __weak typeof(self) mySelf = self;
    [self.tableView setPullDownHandler:^(QFRefreshView *refreshView) {
        if (mySelf.isRefreshing) {
            return ;
        }
        mySelf.isRefreshing = YES;
        mySelf.currentPage = 1;
        [mySelf downloadData];
    }];
    
    //上拉加载更多
    [self.tableView setPullUpHandler:^(QFRefreshView * refreshView) {
        if (mySelf.isRefreshing) {
            return ;
        }
        mySelf.isRefreshing = YES;
        mySelf.currentPage= mySelf.currentPage+1;
        
        [mySelf downloadData];
    }];
}

#pragma mark - 下载数据
- (void)downloadData {
    [[DataEngine sharedInstance] requestCarListWithDictionary:self.queryFilterList pageIndex:self.currentPage Success:^(id respondsData) {
        [self downloadDataSuccess:respondsData];
    } failed:^(NSError *error) {
        
    }];
}

- (void)downloadDataSuccess:(id)respondsData {
    if (self.currentPage == 1) {
        [self.dataArr removeAllObjects];
    }
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:respondsData options:NSJSONReadingMutableContainers error:nil];
    for (NSDictionary *carDict in dict[@"result"][@"seriesitems"]) {
        CarSystemModel *model = [[CarSystemModel alloc] init];
        [model setValuesForKeysWithDictionary:carDict];
        [self.dataArr addObject:model];
    }
    [self.tableView reloadData];
    self.isRefreshing = NO;
    [self.tableView stopFooterViewLoading];
    [self.tableView stopHeaderViewLoading];
}

#pragma mark - 创建滚动视图
- (void)createTableView {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64-49) style:UITableViewStylePlain];
    self.tableView.delegate =self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 80;
    [self.tableView registerNib:[UINib nibWithNibName:@"CarSystemCell" bundle:nil] forCellReuseIdentifier:kCarSystemCellId];
    [self.view addSubview:self.tableView];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CarSystemCell *cell = [tableView dequeueReusableCellWithIdentifier:kCarSystemCellId forIndexPath:indexPath];
    [cell showDataWithModel:self.dataArr[indexPath.row]];
    return cell;
}

//点击cell的时候显示右侧视图
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [UIView animateWithDuration:0.5 animations:^{
        self.grayView.alpha = 0.5;
        self.selectCarTypeView.frame = CGRectMake(50, 20, kScreenWidth-50, kScreenHeight-20);
    }];
    [self postData:indexPath];
}

//向右侧视图发送数据
- (void)postData:(NSIndexPath *)indexPath {
    
    CarSystemModel *systeModel = self.dataArr[indexPath.row];
    self.selectCarTypeView.carSystemModel = systeModel;
    
    //通知右侧界面reloadData
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateSelectCarTypeView" object:nil];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
